package com.zk.yygh.hosp.receiver;

import com.rabbitmq.client.Channel;
import com.zk.yygh.hosp.mapper.ScheduleMapper;
import com.zk.yygh.hosp.service.ScheduleService;
import com.zk.yygh.model.hosp.Schedule;
import com.zk.yygh.vo.msm.MsmVo;
import com.zk.yygh.vo.order.OrderMqVo;
import com.zk.yygh.rabbit.constant.MqConst;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.zk.yygh.rabbit.service.RabbitService;

import java.io.IOException;

/**
 *
 * mq的监听器
 *
 * @author: 张凯
 * @date: 2022/6/21 - 16:41
 */
@Component
public class HospitalReceiver {
    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;

    @Autowired
    private ScheduleMapper scheduleMapper;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
            key = {MqConst.ROUTING_ORDER}
    ))
    public void receiver(OrderMqVo orderMqVo, Message message, Channel channel) throws IOException {
        if (orderMqVo.getAvailableNumber()!=null){
            //--->mongodb<---
            //下单成功更新预约数
            Schedule schedule = scheduleService.getScheduleById(orderMqVo.getScheduleId());
            //设置剩余的预约数量以及可预约数量
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            //更新排班信息
            scheduleService.update(schedule);
        }else {
            //--->MySQL<---
            //取消预约更新预约数
//            Schedule schedule = scheduleMapper.selectById(orderMqVo.getScheduleId());
//            int availableNumber = schedule.getAvailableNumber().intValue() + 1;
//            schedule.setAvailableNumber(availableNumber);
//            scheduleMapper.updateById(schedule);
        }
        //发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if(null != msmVo) {
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }
    }
}
